<?php
header('Content-type:text/html; charset=utf-8');
error_reporting(0);
require ('pscws23/pscws3.class.php');
require_once('DBConfig.php');

class RobotChat{
    
    private $conn;

    public function __construct($conn){
        $this->conn = $conn;
    }

    public function router(){
        if (isset($_GET['message']) && $_GET['message']!="") {
            $message=trim( $_GET['message'] );
            $robotResp = $this->response($message, $this->conn)['answer'];
            $res = $robotResp==null ? "Pardon ?" : $robotResp;
            echo $_GET['jsoncallback'].'('.json_encode($res).')';
        }
    }
    
    public function response($str, $conn){
        @$arr = $this->divWords($str);
        return $this->getBestMatch($arr, $conn);
    }
    
    public function divWords($str){
        $pscws = new PSCWS3('pscws23/dict/dict.xdb');
        $pscws->set_debug(false);
        $res = $pscws->segment($str);
        $len=count($res);
        $ar01=array();
        for($i=0;$i<$len;$i++){
            array_push($ar01, $res[$i]);
        }
        $ar02=array();
        for($i=0;$i<$len;$i++){
            for($j=$len-1; $j>$i; $j--){
                array_push($ar02, $res[$i].$res[$j]);
            }
        }
        $ar03=array();
        for($i=0;$i<$len;$i++){
            for($j=$i+1; $j<$len; $j++){
                for ($k=$j+1; $k < $len; $k++) {
                    array_push($ar03, $res[$i].$res[$j].$res[$k]);
                }
            }
        }
        $ar04=array_merge($ar01,$ar02,$ar03);
        return $ar04;
    }
    
    public function getBestMatch($arr, $conn) {
        $len = count($arr);
        $lastWeightArr=[];//each segment of words
        for ($i=0; $i < $len; $i++) {
            $sql = "select question,answer from ChatDict where question like '%{$arr[$i]}%'";
            $queryRes = array();
            $query = mysql_query($sql, $conn);
            while($row = mysql_fetch_array($query)){
                array_push( $queryRes, ['question'=>$row['question'], 'answer'=>$row['answer']] );
            }
            if($queryRes!=null && count($queryRes)!=0 ){
                $divWeightArr = [];
                for ($k=0; $k<count(queryRes); $k++) {
                    $resMap = $queryRes[$k];
                    $qstWeightArr = [];//question weight
                    for ($j=0; $j < $len; $j++) {
                        $pattern01 = '/'.$arr[$i].'/i';
                        $pattern02 = "/^".$arr[$i]."/i";
                        $pattern03 = '/'.$arr[$i].'$/i';
                        $pattern04 = '/'.$arr[$i].'/i';
                        $qstWeight = 0;
                        if( preg_match($pattern01, $resMap['question']) ){
                            $qstWeight += 50;
                        }
                        if( preg_match($pattern02, $resMap['question']) ){
                            $qstWeight += 30;
                        }
                        if ( preg_match($pattern03, $resMap['question']) ){
                            $qstWeight += 30;
                        }
                        if ( preg_match($pattern04, $resMap['question']) ){
                            $qstWeight += 20;
                        }
                        $qstWeightArr[$arr[$i]]=$qstWeight;
                    }
                    
                    $maxQstWeight = max(array_values($qstWeightArr));
                    $divWeightArr[strval($maxQstWeight)] = $resMap;
                }
            }
            $maxDivWeight = max(array_keys($divWeightArr));
            $lastWeightArr[strval($maxDivWeight)] = $divWeightArr[strval($maxDivWeight)];
        }
        $lastMaxWeight = max(array_keys($lastWeightArr));
        return $lastWeightArr[strval($lastMaxWeight)];
    }
}

$robot = new RobotChat($conn);
$robot->router();
?>